<?php

namespace app\api\controller;

use app\admin\model\pdd\Goods;
use app\common\controller\Api;
use think\Exception;

/**
 * 示例接口
 */
class Pdd extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 测试方法
     *
     * @ApiTitle    (测试名称)
     * @ApiSummary  (测试描述信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/demo/test/id/{id}/name/{name})
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="name", type="string", required=true, description="用户名")
     * @ApiParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    })
     */
    public function test()
    {
        $this->success('返回成功', $this->request->param());
    }


    public function source()
    {
        $res = $this->request->param();
//        $res = unserialize(file_get_contents(RUNTIME_PATH . '1710832457_ppd.json'));
        try {
            $attachment = $res['Attachment']??[];
            $goods_id = $attachment['goods_id']??null;
            if(empty($goods_id)){
                $this->error('数据格式错误');
            }
            $getTime = strlen($res['GetTime']) > 10 ? intval($res['GetTime'] / 1000) : intval($res['GetTime']);
            $data = $res['Data'];
            $hasGoodsProperty = (int)keyExistsInArray($data, 'goodsProperty');
            $good = Goods::get(['goods_id' => $goods_id]);
            if ($good instanceof Goods) {
                $good->data = json_encode($data,JSON_UNESCAPED_UNICODE);
                $good->getTime = $getTime;
                $good->hasGoodsProperty = $hasGoodsProperty;
                $good->save();
            } else {
                $good = Goods::create([
                    'goods_id' => $goods_id,
                    'getTime' => $getTime,
                    'data' => json_encode($data,JSON_UNESCAPED_UNICODE),
                    'hasGoodsProperty' => $hasGoodsProperty
                ]);
            }

            $this->success('接收成功', $good->toArray());
        } catch (Exception $e) {
            $this->error('接收失败', $e->getTraceAsString());
        }
    }


}
